约瑟夫问题
n个人想玩残酷的死亡游戏,游戏规则如下:
n个人进行编号,分别从1到n,排成一个圈,顺时针从1开始数到m,数到m的人被杀,剩下的人继续游戏,活到最后的一个人是胜利者。
请输出最后一个人的编号。
输入n和m值。
输出胜利者的编号。
Sample Input
5 3
Sample Output
4
Hint
第一轮:3被杀第二轮:1被杀第三轮:5被杀第四轮:2被杀
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int data;
struct node *next;
};
struct node*newnode()
{
struct node*t;
t=(struct node*)malloc(sizeof(struct node));
t->next=NULL;
return t;
};
struct node*creat(int n)
{
struct node*head,*p,*tail;
int i;
head=newnode();tail=head;
head->data=1;
for(i=2;i<=n;i++)
{
p=newnode();
p->data=i;
tail->next=p;
tail=p;
}
tail->next=head;
return head;
};
int num(struct node*head,int m,int n)
{
struct node*p,*q;
int num=0;
q=head;
while(q->next!=head)
q=q->next;
//p=q->next;
while(n>1)
{
p=q->next;
num++;
if(num%m==0)
{
q->next=p->next;
free(p);n--;
p=q->next;
}
else
{
q=p;
}
}
return q->data;
}
int main()
{
int n,m,nu;
scanf("%d%d",&n,&m);
struct node*head;
head=creat(n);
nu=num(head,m,n);
printf("%d\n",nu);
return 0;
}
不敢死队问题
说到“敢死队”,大家不要以为我来介绍电影了,因为数据结构里真有这么道程序设计题目,原题如下:
有M个敢死队员要炸掉敌人的一个碉堡,谁都不想去,排长决定用轮回数数的办法来决定哪个战士去执行任务。如果前一个战士没完成任务,则要再派一个战士上去。现给每个战士编一个号,大家围坐成一圈,随便从某一个战士开始计数,当数到5时,对应的战士就去执行任务,且此战士不再参加下一轮计数。如果此战士没完成任务,再从下一个战士开始数数,被数到第5时,此战士接着去执行任务。以此类推,直到任务完成为止。
这题本来就叫“敢死队”。“谁都不想去”,就这一句我觉得这个问题也只能叫“不敢死队问题”。今天大家就要完成这道不敢死队问题。我们假设排长是1号,按照上面介绍,从一号开始数,数到5的那名战士去执行任务,那么排长是第几个去执行任务的?
输入包括多试数据,每行一个整数M(0<=M<=10000)(敢死队人数),若M==0,输入结束,不做处理。
输出一个整数n,代表排长是第n个去执行任务。
Sample Input
9
6
223
0
Sample Output
2
6
132
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int data;
struct node *next;
};
struct node*newnode()
{
struct node*t;
t=(struct node*)malloc(sizeof(struct node));
t->next=NULL;
return t;
};
struct node*creat(int n)
{
struct node*head,*p,*tail;
int i;
head=newnode();
tail=head;
head->data=1;
for(i=2; i<=n; i++)
{
p=newnode();
p->data=i;
tail->next=p;
tail=p;
}
tail->next=head;
return head;
};
void num(struct node*head,int m,int n)
{
struct node*p,*q;
int num=0,count=0;
q=head;
while(q->next!=head)
q=q->next;
while(1)
{
p=q->next;
num++;
if(num%m==0)
{
count++;
if(p->data==1)
{
printf("%d\n",count);
return ;
}
q->next=p->next;
free(p);
}
else
{
q=p;
}
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF&&n)
{
struct node*head;
head=creat(n);
num(head,5,n);
}
return 0;
}